import { _decorator, Color, Component, Label, Node, ProgressBar, Sprite, SpriteFrame, UITransform } from 'cc';
import { Core } from './Core/Core';
import { BattleManager } from './BattleManager';
import { ResourceManager } from './Core/ResourceManager';
import { PicPath } from './Config/ResourceConfig';
import { Util } from './Util';
const { ccclass, property } = _decorator;

@ccclass('WallManager')
export class WallManager extends Component {
    private static _instance: WallManager | null = null;
    lbHp: Label;
    public static get Instance(): WallManager {
        if (!WallManager._instance) {
            console.error("WallManager 尚未初始化！请确保场景中存在 WallManager 节点");
        }
        return WallManager._instance!;
    }


    width = 400; // 血条和护盾条的初始宽度
    height = 800; // 血条和护盾条的高度
    dp: number = 0; // 城墙防御
    dodge: number = 0; // 城墙闪避

    ndHP: Node
    ndSheild: Node
    hp: number = 100
    maxHp: number = 100
    sheild: number = 0;
    originalSheild: number = 0; // 用于记录护盾的初始值




    protected onLoad(): void {
        WallManager._instance = this; // 确保单例在 onLoad 时初始化
        
        this.ndHP=this.node.getChildByName("PB_HP") 
        this.ndSheild = this.node.getChildByName("PB_Sheild");
        // 城墙血量 = 玩家血量的10% + 城墙等级*100
        //this.hp = Math.floor(this.calPlayerHp()) + Core.Instance.wallLevel * 100
        // 城墙防御 = 玩家防御的10% + 城墙等级*10
        //this.dp = Math.floor(this.calPlayerDp()) + Core.Instance.wallLevel * 1
        this.lbHp = this.ndHP.getChildByName("Label").getComponent(Label)


        this.width = Core.Instance.width;
        this.height = Core.Instance.height;
    }
    protected onEnable(): void {
        console.log("wallmanager enable, ISNEWPLAYER",Core.Instance.isNewPlayer)

        this.hp = this.maxHp = BattleManager.Instance.wallHpBegin = Core.Instance.wallHp  + Math.floor(this.calPlayerHp())
        this.dp = Math.floor(this.calPlayerDp())
        this.dodge = Util.roundToOne(this.calPlayerDodge())
        console.log("aaaaaaawall dp dodge:", this.dp , this.dodge)

        // //初始化血量
        // if(Core.Instance.isNewPlayer){
        //     BattleManager.Instance.wallHpBegin = Core.Instance.wallHP = this.hp = this.maxHp
        //     console.log("wallmanager enable, ISNEW")
        // }else{
        //     this.hp = Core.Instance.wallHP
        //     console.log("wallmanager enable, IS NOT NEW")
        // }


        this.updateHPDisplay()
        
    }

    hurt(value: number) { // sheild100


        let damageReduction = Math.sqrt(this.dp) / (Math.sqrt(this.dp) + 20); // 这个公式什么意思 dp越高，伤害减免越多，但收益递减
        let actualDamage = Math.max(value * (1 - damageReduction), 1);
        
        // 当有sheild时，先扣除sheild
        if (this.sheild > 0) {
            this.originalSheild = this.sheild;
            this.sheild -= value;
            this.ndSheild.getComponent(ProgressBar).progress = this.sheild / this.originalSheild;
            this.updateShieldDisplay();
            return; // 如果护盾值大于0，则不再扣除血量

        } else {
            this.sheild = 0;
        }
        // 扣除血量
        this.hp -= actualDamage;
        console.log("WallManager value damageReduction actualDamage dp", value,damageReduction,actualDamage, this.dp)
        if (this.hp > 0) {
            this.updateShieldDisplay();
            //this.slashOnce();
            //NumberText.show(`${Math.ceil(value)}`, this.node.worldPosition);
            
            this.updateHPDisplay()
            //if(this.hp < this.maxHp/2){
                // 切换残破的城墙的图片
                //this.node.getComponent(Sprite).spriteFrame = Core.Instance.textureMap.get("Wall2")[0];
                //this.node.getComponent(Sprite).spriteFrame = ResourceManager.Instance.loadRes(PicPath.wall2, SpriteFrame)[0];
                // this.node.getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes(PicPath.wall2);
            //}
        } else {
            this.hp = 0;
            this.updateHPDisplay()
            //this.node.getComponent(Sprite).spriteFrame = ResourceManager.Instance.loadRes(PicPath.wall2, SpriteFrame)[0];
            //this.node.getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes(PicPath.wall2);
            ResourceManager.Instance.loadRes<SpriteFrame>(PicPath.wall2+"/spriteFrame")
            .then((spriteFrame) => {
                this.node.getComponent(Sprite).spriteFrame = spriteFrame;
            })
            .catch((error) => {
                console.error("加载残破城墙图片失败:", error);
            });
            //this.node.getChildByName('Icon').getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(PicPath[Core.Instance.currentSkill+this.node.name])
            Core.Instance.gameResult = false;
            BattleManager.Instance.endGame(false);


        }


    }

    addHp(value: number) {
        this.hp += value;
        if (this.hp > this.maxHp) {
            this.hp = this.maxHp;
        }
        this.updateHPDisplay()
    }

    calPlayerHp() {
        let playerHp = 0;
        Core.Instance.selectedPlayers.forEach(pt => {
            playerHp += Core.Instance.players.get(pt).getHp();
        });
        return playerHp * 0.05
    }

    calPlayerDp() {
        let playerDp = 0;
        Core.Instance.selectedPlayers.forEach(pt => {
            playerDp += Core.Instance.players.get(pt).getDp();
        });
        console.log("aaaaaaaaplayerDp in calPlayerDp",playerDp)
        return playerDp * 0.1
    }

    calPlayerDodge(){
        let playerDodge = 0;
        Core.Instance.selectedPlayers.forEach(pt => {
            playerDodge += Core.Instance.players.get(pt).getDodge();
        });
        console.log("aaaaaaaaplayerDodge in calPlayerDodge",playerDodge)
        return playerDodge * 0.1
    }

    updateShieldDisplay() {
        // 当护盾为0时完全隐藏护盾条
        if (this.sheild <= 0) {
            this.ndSheild.active = false;
            this.ndHP.getComponent(UITransform).width = this.ndHP.getComponent(ProgressBar).totalLength = this.width; // 恢复血条宽度
            return;
        }else {
            this.ndSheild.active = true;
            //this.ndSheild.getComponent(ProgressBar).progress = this.sheild / this.hp; // 假设护盾最大值为1000
            this.ndHP.getComponent(UITransform).width = this.ndHP.getComponent(ProgressBar).totalLength = this.width - (this.sheild / this.hp) * this.width; // 根据护盾宽度调整血条宽度
            this.ndSheild.getComponent(UITransform).width = this.ndSheild.getComponent(ProgressBar).totalLength = this.width - this.ndHP.getComponent(UITransform).width; // 根据护盾宽度调整护盾条宽度
            this.ndSheild.setPosition(this.ndSheild.getComponent(UITransform).width, this.ndSheild.getComponent(UITransform).height,0);
        }
    }

    updateHPDisplay(){
        this.lbHp.string = Math.round(this.hp) +"/" + this.maxHp
        this.ndHP.getComponent(ProgressBar).progress = this.hp / this.maxHp;


    }



    private slashOnce() {
        this.node.getComponent(Sprite).color = Color.RED;
        this.scheduleOnce(() => this.node.getComponent(Sprite).color = Color.WHITE, 0.15);
    }

    
    start() {

    }

    update(deltaTime: number) {
        
    }

    public getHpPercent() {
        return this.hp / this.maxHp;
    }
}


